package org.hhf;

import org.hhf.command.CommandProcessor;

import java.util.Scanner;

/**
 * nano-redis 主程序
 */
public class App {
    public static void main(String[] args) {
        System.out.println("=====================================");
        System.out.println("Welcome to nano-redis v1.0");
        System.out.println("A lightweight Redis implementation");
        System.out.println("=====================================");
        
        CommandProcessor processor = new CommandProcessor();
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("nano-redis> Ready to accept connections");
        System.out.println("Type 'QUIT' or 'EXIT' to stop the server");
        
        while (true) {
            System.out.print("nano-redis> ");
            String input = scanner.nextLine().trim();
            
            if (input.isEmpty()) {
                continue;
            }
            
            if ("QUIT".equalsIgnoreCase(input) || "EXIT".equalsIgnoreCase(input)) {
                System.out.println("Goodbye!");
                break;
            }
            
            try {
                Object result = processor.processCommand(input);
                System.out.println(formatResponse(result));
            } catch (Exception e) {
                System.out.println("-ERR " + e.getMessage());
            }
        }
        
        scanner.close();
    }
    
    /**
     * 格式化响应结果
     */
    private static String formatResponse(Object result) {
        if (result == null) {
            return "(nil)";
        }
        
        String response = result.toString();
        
        // 简单的Redis协议解析
        if (response.startsWith("+")) {
            return response.substring(1);
        } else if (response.startsWith("-")) {
            return response; // 保持错误格式
        } else if (response.startsWith(":")) {
            return response.substring(1);
        } else if (response.startsWith("$")) {
            if (response.equals("$-1")) {
                return "(nil)";
            }
            // 简化处理，返回原始响应
            return response;
        } else if (response.startsWith("*")) {
            // 简化处理数组响应
            return response;
        }
        
        return response;
    }
}
